<?php

namespace addons\yungift\model;

use addons\yungift\library\ModelTrait;
use addons\yungift\library\Super;
use app\common\model\User;
use think\Model;
use traits\model\SoftDelete;

/**
 * 成员模型
 */
class Member extends Model
{
    use ModelTrait;
    use SoftDelete;

    // 表名,不含前缀
    protected $name = 'yungift_member';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $deleteTime = 'deleted_at';
    protected $updateTime = 'updated_at';
    protected $createTime = 'created_at';

    // 不显示的字段
    protected $hidden = ['deleted_at'];

    protected $resultSetType = 'collection';

    public function scopeShow($query)
    {
        return $query->where('status', '=', self::STATUS_NORMAL);
    }

    // 用户数据
    public function userData()
    {
        return $this->hasOne(User::class, 'id', 'user_id');
    }

    // 分组数据
    public function groupData()
    {
        return $this->belongsTo(Group::class, 'group_id', 'id');
    }

    // fix: 关联查询用
    public function fundUser()
    {
        return new FundUser();
    }

    public function getGroupTextAttr($value, $data)
    {
        if (empty($data['group_id'])) {
            return '未分组';
        }

        return $this->groupData->name ?? '已删除';
    }

    // 性别
    const GENDER_MALE   = 1;
    const GENDER_FEMALE = 2;
    const GENDER_NONE   = 3;

    public static function getGenderList()
    {
        return [self::GENDER_MALE => __('男'), self::GENDER_FEMALE => __('女'), self::GENDER_NONE => '未知'];
    }

    public function getGenderTextAttr($value, $data)
    {
        $optionList = self::getGenderList();

        return $optionList[$data['gender']] ?? '';
    }

    // 状态
    const STATUS_NORMAL = 1;
    const STATUS_HIDDEN = 2;

    public static function getStatusList()
    {
        return [self::STATUS_NORMAL => __('Normal'), self::STATUS_HIDDEN => __('屏蔽')];
    }

    public function getStatusTextAttr($value, $data)
    {
        $statusList = self::getStatusList();

        return $statusList[$data['status']] ?? $data['status'];
    }

    // 获取脱敏的登录码
    public function getCodeMixAttr($value, $data)
    {
//        if ($data['code'] && $data['code'] != md5($data['init_code'])) {
//            return '***';
//        }
//
//        return $data['init_code'] ? Super::stringHide($data['init_code']) : '无';
        return $data['code'] ? '有' : '无';
    }


    // 用户头像
    public function getAvatarUrlAttr($value, $data)
    {
        return $value ? cdnurl($value, true) : $value;
    }

}
